匹配单个字符

匹配单个字符

代码 功能
. 匹配任意1个字符(除了\n)
[] 匹配[]中列举的字符
\d 匹配数字,即0-9
\D 匹配非数字,即不是数字
\s 匹配空白,即空格、Tab键
\S 匹配非空白
\w 匹配非特殊字符,即a-z、A-Z、0-9、_、汉字
\W 匹配特殊字符,即非字母、非数字、非汉字、非下划线

示例:

import re

# . 匹配任意1个字符(除了\n)
# []    匹配[]中列举的字符
# \d    匹配数字,即0-9
# \D    匹配非数字,即不是数字
# \s    匹配空白,即空格、Tab键
# \S    匹配非空白
# \w    匹配非特殊字符,即a-z、A-Z、0-9、_、汉字
# \W    匹配特殊字符,即非字母、非数字、非汉字、非下划线

# # . 匹配任意1个字符(除了\n)
# # 匹配数据
# result = re.match('itcast.', 'itcast1')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# []    匹配[]中列举的字符
# 匹配数据
# result = re.match('itcast[123abc]', 'itcast1')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \d    匹配数字,即0-9 [0123456789]
# 匹配数据
# result = re.match('itcast\d', 'itcast2') # 'itcast\d' <==> 'itcast[0-9]'
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \D    匹配非数字,即不是数字
# result = re.match('itcast\D', 'itcasta')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \s    匹配空白,即空格、Tab键
# result = re.match('itcast\s111', 'itcast\t111')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \S    匹配非空白
# result = re.match('itcast\S', 'itcast)')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \w    匹配非特殊字符,即a-z、A-Z、0-9、_、汉字
# result = re.match('itcast\w', 'itcast_)')
#
# # 获取数据
# if result:
#     info = result.group()
#     print(info)
# else:
#     print('没有匹配到')

# \W    匹配特殊字符,即非字母、非数字、非汉字、非下划线
result = re.match('itcast\W', 'itcast@')

# 获取数据
if result:
    info = result.group()
    print(info)
else:
    print('没有匹配到')